package models

import (
	"chat/utils"
	"fmt"

	"gorm.io/gorm"
)

// 人员关系
type Contact struct {
	gorm.Model
	OwnerId     uint   `json:"owner_id" gorm:"关系创建者ID"`
	OwnerName   string `json:"owner_name" gorm:"关系创建者名称"`
	TargetId    uint   `json:"target_id" gorm:"关系接收者ID"`
	TargetName  string `json:"target_name"  gorm:"关系接收者名称"`
	Type        int    `json:"type" gorm:"关系类型"` // Type of contact 1:好友 2：群组  3：
	Desc        string `json:"desc" gorm:"描述"`   // Description of this contact
	AgreeOrNot  bool   `json:"agree_or_not" gorm:"是否同意添加 好友 or 群组"`
	ApplyTime   string `json:"apply_time" gorm:"同意添加好友时间"`
	ApplyAvatar string `json:"apply_avatar" gorm:"申请人头像"` //
}

func (table *Contact) TableName() string {
	return "contact_basic"
}

func SearchFriend(userId uint) []UserBasic {
	contacts := make([]Contact, 0)
	objIds := make([]uint64, 0)
	utils.Mysql.Where("owner_id = ? and type = 1", userId).Find(&contacts)
	for _, v := range contacts {
		fmt.Printf("v: %v\n", v)
		objIds = append(objIds, uint64(v.TargetId))
	}
	users := make([]UserBasic, 0)
	utils.Mysql.Where("id in ? ", objIds).Find(&users)
	return nil
}

func ApplyFriend(contact Contact) (Contact, string, error) {
	var existingContact Contact
	err := utils.Mysql.Where("owner_id = ? AND target_id = ?", contact.OwnerId, contact.TargetId).First(&existingContact).Error
	var str string
	if err == nil {
		// 如果存在相同的 ownerId 和 targetId，则直接返回已存在的记录
		str = "已发送过请求，请勿重复发送"
	} else {
		str = "发送好友请求成功"
		err = utils.Mysql.Create(&contact).Error
	}

	return contact, str, err
}

func GetApplyList(id string) ([]*Contact, []*Contact) {
	friends := make([]*Contact, 0)
	groups := make([]*Contact, 0)
	utils.Mysql.Model(&friends).Where("(target_id = ? OR owner_id =?) AND type=1", id, id).Find(&friends)
	utils.Mysql.Model(&friends).Where(" owner_id =? AND type=2", id).Find(&groups)
	return friends, groups
}

func AgreeFriendApply(contact Contact) (Contact, error) {
	err := utils.Mysql.Model(&contact).Updates(&contact).Error
	return contact, err
}
